package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MovementsService {
    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;
    /**
     * 首页-访客
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        //1.查询访问时间
        String key = Constants.VISITORS_USER;
        String hashKey = String.valueOf(UserHolder.getUserId());
        String value = (String) redisTemplate.opsForHash().get(key,hashKey);
        Long date = StringUtils.isEmpty(value) ? null : Long.valueOf(value);
        //2.调用Api查询访问数据列表List<Visitors>
        List<Visitors> list = visitorsApi.queryMyVisitors(date,UserHolder.getUserId());
        if (CollUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        //3.提取用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        //4.查看用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //5.构造返回
        List<VisitorsVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            if (userInfo == null){
                VisitorsVo vo = VisitorsVo.init(userInfo, visitors);
                vos.add(vo);
            }
        }
        return vos;
    }
}
